package com.example.stmall.manager.controller.api;

import com.example.stmall.manager.entity.Goods;
import com.example.stmall.manager.entity.Result;
import com.example.stmall.manager.service.GoodsService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/api/goods")
public class APIGoodsController {

    @Autowired
    private GoodsService goodsService;
    /**
     * 添加，POST
     */
    @PostMapping
    public Result add(@RequestBody Goods goods){
        try{
            int code = goodsService.add(goods);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    /**
     * 删除
     */
    @DeleteMapping
    public Result remove(Integer id){
        try{
            int code = goodsService.remove(id);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();;
            return Result.error(e.getMessage());
        }
    }
    /**
     * 改，put
     */
    @PutMapping
    public Result edit(@RequestBody Goods goods){
        try {
            int code = goodsService.edit(goods);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * ID查 get
     */
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id){
        try {
            Goods goods = goodsService.getById(id);
            return Result.success(goods);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查所有
     * @param page
     * @param limit
     * @param goods
     * @return
     */
    @GetMapping
    public Result get(Integer page,Integer limit,Goods goods){
        if(page == null){
            List<Goods> list = goodsService.search(goods);
            return Result.success(list);
        }else{
            PageInfo pageInfo = goodsService.searchByPage(page,limit,goods);
            return Result.success(pageInfo);
        }
    }
}
